package com.snail.billing.fragment;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.net.HttpApp;
import com.android.net.HttpResult;
import com.android.net.HttpSession;
import com.android.net.OnHttpResultListener;
import com.android.os.Page;
import com.android.util.AlertUtil;
import com.android.util.ResUtil;
import com.snail.billing.DataCache;
import com.snail.billing.PaymentConst;
import com.snail.billing.PaymentParams;
import com.snail.billing.Resource;
import com.snail.billing.data.PaymentLogic;
import com.snail.billing.json.JsonBase;
import com.snail.billing.json.JsonCards;
import com.snail.billing.json.JsonState;
import com.snail.billing.session.CaptchaSession;
import com.snail.billing.session.CardsSession;
import com.snail.billing.session.PayOneSession;
import com.snail.billing.session.StateImprestSession;
import com.tencent.mm.sdk.modelpay.PayReq;

public class StateImprestFragment2 extends Page implements View.OnClickListener, AdapterView.OnItemClickListener, OnHttpResultListener {

	private TextView textTitle;
	private View buttonBack;

	private View layout;
	private TextView textAccount;
	private TextView textProduce;
	private TextView textPrice;
	private ListView listView;
	private TextView textPrice2;
	private View buttonPay;
	private List<Map<String, Object>> data;
	private SimpleAdapter adapter;

	private StateImprestSession stateSession;
	private JsonState jsonState;

	private HttpApp httpApp;
	private CardsSession cardsSession;
	private CaptchaSession captchaSession;
	private PayOneSession paySession;
	private int position = -1;

	@Override
	public int createLayoutId() {
		return ResUtil.getLayoutId(Resource.layout.snailbilling_payment_state_activity);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		textTitle = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_title_text));
		textTitle.setText("选择充值方式");
		buttonBack = findViewById(ResUtil.getViewId(Resource.id.snailbilling_title_button_back));
		buttonBack.setOnClickListener(this);
		//
		layout = findViewById(ResUtil.getViewId(Resource.id.snailbilling_payment_state_layout));
		layout.setVisibility(View.GONE);
		textAccount = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_payment_state_text_account));
		textAccount.setText("账号：" + DataCache.getInstance().importParams.account);
		textProduce = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_payment_state_text_produce));
		textProduce.setVisibility(View.GONE);
		textPrice = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_payment_state_text_price));
		textPrice.setText(Html.fromHtml("<span>金额：<font color=\"#ff363f\">￥" + new BigDecimal(DataCache.getInstance().importParams.price) + "</font>元</span>"));
		listView = (ListView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_payment_state_list_view));
		listView.setOnItemClickListener(this);
		textPrice2 = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_payment_state_text_price2));
		textPrice2.setText(Html.fromHtml("<span>你需支付的RMB金额：\t<font color=\"#ff363f\">￥" + new BigDecimal(DataCache.getInstance().importParams.price) + "\t</font>元</span>"));
		buttonPay = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_payment_state_button_pay));
		buttonPay.setOnClickListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		httpApp = new HttpApp(getContext());
		requestPayState();
	}

	@Override
	public void onClick(View v) {
		if (v.equals(buttonBack)) {
			getPageManager().backward();
		} else if (v.equals(buttonPay)) {
			if (position == -1) {
				AlertUtil.show(getContext(), "请选择充值方式");
				return;
			}
			String index = jsonState.getIndexs()[position];
			int platformId = jsonState.getPlatforms().get(index).getPlatformId();
			String platformName = jsonState.getPlatforms().get(index).getName();
			DataCache.getInstance().paymentParams = new PaymentParams();
			DataCache.getInstance().paymentParams.platformId = platformId;
			DataCache.getInstance().paymentParams.platformName = platformName;
			requestCaptcha();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		this.position = position;
		ViewGroup group = (ViewGroup) parent;
		for (int i = 0; i < group.getChildCount(); i++) {
			ViewGroup group2 = (ViewGroup) group.getChildAt(i);
			ImageView imageView = (ImageView) group2.findViewById(ResUtil.getViewId(Resource.id.snailbilling_state_image_check));
			if (position == i) {
				imageView.setImageResource(ResUtil.getDrawableId(Resource.drawable.snailbilling_check_on));
			} else {
				imageView.setImageResource(ResUtil.getDrawableId(Resource.drawable.snailbilling_check_off));
			}
		}
	}

	private void requestPayState() {
		if (jsonState != null && jsonState.getPlatforms() != null) {
			listView.setAdapter(createAdapter());
			layout.setVisibility(View.VISIBLE);
		} else {
			stateSession = new StateImprestSession();
			httpApp.setOnHttpResultListener(this);
			httpApp.request(stateSession);
		}
	}

	private void requestCaptcha() {
		httpApp.setDialogAutoDismiss(false);
		captchaSession = new CaptchaSession(0);
		httpApp.setOnHttpResultListener(this);
		httpApp.request(captchaSession);
	}

	private void requestCards() {
		httpApp.setDialogAutoDismiss(false);
		cardsSession = new CardsSession();
		httpApp.setOnHttpResultListener(this);
		httpApp.request(cardsSession);
	}

	private void requestPay() {
		paySession = new PayOneSession();
		httpApp.setOnHttpResultListener(this);
		httpApp.request(paySession);
	}

	@Override
	public void onHttpResult(HttpResult httpResult) {
		if (httpResult.isSucceed()) {
			HttpSession httpSession = httpResult.getHttpSession();
			if (httpSession.equals(stateSession)) {
				jsonState = new JsonState((String) stateSession.getResponseData());
				if (jsonState != null && jsonState.getPlatforms() != null) {
					listView.setAdapter(createAdapter());
					layout.setVisibility(View.VISIBLE);
				}
			} else if (httpSession.equals(captchaSession)) {
				if (captchaSession.isUseCaptcha()) {
					httpApp.dialogDismiss();
					Toast.makeText(getContext(), "需要验证码，请联系计费", Toast.LENGTH_SHORT).show();
					return;
				}
				requestCards();
			} else if (httpSession.equals(cardsSession)) {
				JsonCards jsonCards = new JsonCards((String) cardsSession.getResponseData());
				if (jsonCards.getCode() != 1) {
					httpApp.dialogDismiss();
					Toast.makeText(getContext(), jsonCards.getMessage(), Toast.LENGTH_SHORT).show();
					return;
				}
				if (jsonCards.getCards().size() == 0) {
					httpApp.dialogDismiss();
					Toast.makeText(getContext(), "没有面值卡信息", Toast.LENGTH_SHORT).show();
					return;
				}
				for (JsonCards.Card card : jsonCards.getCards()) {
					if (card.getPrice().doubleValue() == new BigDecimal(1).doubleValue()) {
						DataCache.getInstance().paymentParams.card = card;
						break;
					}
				}
				if (DataCache.getInstance().paymentParams.card == null) {
					httpApp.dialogDismiss();
					Toast.makeText(getContext(), "没有1元的面值卡", Toast.LENGTH_SHORT).show();
					return;
				}
				BigDecimal allPrice = new BigDecimal(DataCache.getInstance().importParams.price);
				BigDecimal onePrice = DataCache.getInstance().paymentParams.card.getPrice();
				DataCache.getInstance().paymentParams.amount = allPrice.divide(onePrice).intValue();
				requestPay();
			} else if (httpSession.equals(paySession)) {
				String jsonString = (String) paySession.getResponseData();
				JsonBase result = new JsonBase(jsonString);
				if (result.getCode() == 1) {
					PaymentLogic paymentLogic = new PaymentLogic(getPageManager(), PaymentLogic.STATE_IMPREST2);
					try {
						String orderResponse = jsonString;
						DataCache.getInstance().paymentParams.orderResponse = orderResponse;
						int platformId = DataCache.getInstance().paymentParams.platformId;
						if (platformId == PaymentConst.TYPE_ALIPAY_APP) {
							JSONObject paymentParams = new JSONObject(orderResponse).getJSONObject("paymentParams");
							final String source = paymentParams.getString("source");
							//
							paymentLogic.alipayApp(source);
							return;
						}
						if (platformId == PaymentConst.TYPE_UPOMP2) {
							JSONObject paymentParams = new JSONObject(orderResponse).getJSONObject("paymentParams");
							String unionMobilePayImprestSubmit = paymentParams.getString("unionMobilePayImprestSubmit");
							byte[] to_upomp = unionMobilePayImprestSubmit.getBytes();
							//
							paymentLogic.upompApp(to_upomp);
							return;
						}
						if (platformId == PaymentConst.TYPE_ALIPAY_WEB) {
							paymentLogic.alipayWeb();
							return;
						}
						if (platformId == PaymentConst.TYPE_TENPAY) {
							paymentLogic.tenpayWeb();
							return;
						}
						if (platformId == PaymentConst.TYPE_WECHAT) {
							JSONObject paymentParams = new JSONObject(orderResponse).getJSONObject("paymentParams");
							PayReq payReq = new PayReq();
							payReq.appId = paymentParams.getString("appid");
							payReq.partnerId = paymentParams.getString("partnerid");
							payReq.prepayId = paymentParams.getString("prepayid");
							payReq.nonceStr = paymentParams.getString("noncestr");
							payReq.timeStamp = paymentParams.getString("timestamp");
							payReq.packageValue = "Sign=WXPay";
							payReq.sign = paymentParams.getString("sign");
							//
							paymentLogic.wxpayApp(payReq);
							return;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					Toast.makeText(getContext(), result.getMessage(), Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	private SimpleAdapter createAdapter() {
		data = new ArrayList<Map<String, Object>>();
		for (String index : jsonState.getIndexs()) {
			JsonState.Platform platform = jsonState.getPlatforms().get(index);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put(MyAdapter.TEXT, platform.getName());
			map.put(MyAdapter.TEXT2, "");
			int drawableId = ResUtil.getDrawableId(PaymentConst.IMAGE.get(platform.getPlatformId()));
			if (drawableId == 0) {
				drawableId = ResUtil.getDrawableId(Resource.drawable.snailpay_icon_empty);
			}
			map.put(MyAdapter.IMAGE, drawableId);
			data.add(map);
		}
		//
		int resource = ResUtil.getLayoutId(Resource.layout.snailbilling_payment_state_item);
		String[] from = { MyAdapter.TEXT, MyAdapter.TEXT2 };
		int[] to = { ResUtil.getViewId(Resource.id.snailbilling_state_text), ResUtil.getViewId(Resource.id.snailbilling_state_text2) };
		adapter = new MyAdapter(getContext(), data, resource, from, to);
		return adapter;
	}

	private class MyAdapter extends SimpleAdapter {

		private static final String IMAGE = "image";
		private static final String TEXT = "text";
		private static final String TEXT2 = "text2";

		public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = super.getView(position, convertView, parent);
			//
			ImageView imageView = (ImageView) convertView.findViewById(ResUtil.getViewId(Resource.id.snailbilling_state_image));
			Object image = data.get(position).get(IMAGE);
			if (image != null) {
				if (image instanceof Integer) {
					int resId = (Integer) image;
					imageView.setImageResource(resId);
				} else if (image instanceof String) {
					String filePath = (String) image;
					Bitmap bitmap = BitmapFactory.decodeFile(filePath);
					imageView.setImageBitmap(bitmap);
				}
			}
			//
			Object text2 = data.get(position).get(TEXT2);
			if (TextUtils.isEmpty((String) text2)) {
				View view = convertView.findViewById(ResUtil.getViewId(Resource.id.snailbilling_state_text2));
				view.setVisibility(View.GONE);
			}
			return convertView;
		}
	}

}
